#include "LoginServer.h"
#include "HttpConnection.h"
#include "../log.h"
#include "../utilities.h"
#include "../AsioIoContextPool.h"
#include "../Singleton.h"

#include <boost/beast/core/error.hpp>

LoginServer::LoginServer(boost::asio::io_context& ioc, uint16_t port)
:_acceptor(ioc, tcp::endpoint(tcp::v4(), port))
,_ioc(ioc)
{
    log_info("LoginServer listening on port: {}", port);
}


void LoginServer::Start()
{
    auto self = shared_from_this();
    
    auto& ioContext = Singleton<AsioIoContextPool>::GetInstance()->GetIoContext();
    std::shared_ptr<HttpConnection> conn = std::make_shared<HttpConnection>(ioContext);

    _acceptor.async_accept(conn->GetSocket(),[self, conn](boost::beast::error_code ec)
        {
            try
            {
                if(ec)
                {
                    log_warning("Accept error: {}", ec.message());
                    //放弃该链接，继续监听
                    self->Start();
                    return;
                }
                log_info("Accepted connection from: {}", EndpointToString(conn->GetSocket().remote_endpoint()));
            
                conn->Start(); //开始处理请求
                self->Start(); //继续监听下一个连接
            }
            catch (const std::exception& exp)
            {
                log_error("LoginServer::Start exception {}", exp.what()); 
            }
        });
}